import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheDemo {

	private Map<String,Object> cache = new HashMap<String,Object>();
	private ReadWriteLock rwl = new ReentrantReadWriteLock();
	
	public static void main(String[] args) {

	}
	
	public /*synchronized*/ Object getData(String key) {
		rwl.readLock().lock();
		Object value = null;
		try{
			value = cache.get(key);
			if(value == null){
				rwl.readLock().unlock();//tag1
				rwl.writeLock().lock();
				try{
					if(value == null){//防止其他线程已经进入到了tag1中然后再做判断
						System.out.println("queryDB...");
						value = "get value from DB";
					}
				}finally{
					rwl.writeLock().unlock();
				}
				rwl.readLock().lock();
			}
		}finally{
			rwl.readLock().unlock();
		}
		return value;
	}

}
